<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import Cookies from 'js-cookie';
import { getCodeImg } from '@/api/login';
import settings from '@/config/settings';

import useUserStore from '@/store/modules/user';
import { decrypt, encrypt } from '@/utils/jsencrypt';

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: '',
});

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref<any>(undefined);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true },
);

function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set('username', loginForm.value.username, { expires: 30 });
        Cookies.set('password', encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 });
      }
      else {
        // 否则移除
        Cookies.remove('username');
        Cookies.remove('password');
        Cookies.remove('rememberMe');
      }
      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then((res) => {
          if (res.code === 299) {
            loading.value = false;
            return ElMessageBox.alert('系统检测到当前账号已被禁用，无法登录本系统', {
              title: '提醒',
              type: 'warning',
              cancelButtonText: '关闭',
            });
          }
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== 'redirect') {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
            // sessionStorage.setItem(settings.isAdminName, true);
            // router.push({ path: redirect.value || "/", query: otherQueryParams })
          router.push({ path: '/index', query: otherQueryParams });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

function getCode() {
  getCodeImg().then(({ data: res }) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${res.img}`;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get('username');
  const password = Cookies.get('password');
  const rememberMe = Cookies.get('rememberMe');
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

getCode();
getCookie();
</script>

<template>
  <div class="login-route">
    <div class="login-login absolute left-[30px] top-[30px] h-[75px] w-[326px]">
      <img src="@/assets/images/logo.png" class="h-full w-full" alt="" />
    </div>
    <div class="login-content">
      <div class="login-content__header">
        {{ settings.title }}
      </div>
      <el-form
        ref="loginRef"
        hide-required-asterisk
        :model="loginForm"
        :rules="loginRules"
        class="login-form relative"
      >
        <h3 class="title !text-left !text-[30px]">
          登录
        </h3>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="账号"
          >
            <template #prefix>
              <svg-icon icon-class="user" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <svg-icon icon-class="password" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="captchaEnabled" prop="code">
          <el-input
            v-model="loginForm.code"
            size="large"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
            </template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" class="login-code-img" @click="getCode" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" color="#165DFF" style="margin: 0 0 25px">
          记住密码
        </el-checkbox>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="large"
            type="primary"
            class="!h-[54px]"
            color="#165DFF"
            style="width: 100%"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div v-if="register" style="float: right">
            <router-link class="link-type" to="/register">
              立即注册
            </router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .login-route {
  display: flex;
  align-items: center;
  justify-content: end;
  height: 100vh;
  padding: 0 200px;
  background-image: url('../assets/images/login-background.jpg');
  background-size: cover;
}

.el-checkbox,
:deep(.el-checkbox) {
  --el-checkbox-checked-bg-color: #165dff;
  --el-checkbox-checked-text-color: #165dff;
  --el-checkbox-checked-input-border-color: #165dff;

  margin-bottom: 20px;
}

.title {
  margin: 0 auto 30px;
  color: #131313;
  text-align: center;
}

.login-content__header {
  color: #fff;
  font-family: 'Alimama ShuHeiTi';
  font-size: 36px;
  font-weight: 700;
  line-height: 48px;
  text-align: center;
  text-underline-position: from-font;
  text-decoration-skip-ink: none;
}

.login-form {
  width: 520px;
  margin-top: 40px;
  padding: 40px 35px;
  border-radius: 6px;
  background: #fff;

  :deep() {
    .el-input__wrapper {
      background: #f2f3f5 !important;
    }
  }

  .el-input {
    --el-input-border-color: rgb(0 0 0 / 0%);
    --el-border: rgb(0 0 0 / 0%);

    height: 56px;

    input {
      height: 56px;
    }
  }

  .input-icon {
    width: 14px;
    height: 39px;
    margin-left: 0;
  }
}

.login-tip {
  color: #bfbfbf;
  font-size: 13px;
  text-align: center;
}

.login-code {
  width: calc(100% - 63% - 20px);
  height: 56px;
  margin-left: 20px;
  float: right;

  img {
    vertical-align: middle;
    cursor: pointer;
  }
}

.el-login-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 40px;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  line-height: 40px;
  text-align: center;
}

.login-code-img {
  height: 56px;
  //padding-left: 12px;
}
</style>
